package com.mjk.common.tools.xml;

import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtils {

    /**
     * 是否是xml格式的字符串
     */
    public static boolean isXML(String str) {
        try {
            DocumentHelper.parseText(str);
        } catch (DocumentException e) {
            return false;
        }
        return true;
    }

    /**
     * 对象转xml
     *
     * @param obj 对象
     */
    public static String beanToXml(Object obj) {
        return beanToXml(obj, false);
    }

    public static String beanToXml(Object obj, boolean isNull) {
        if (null == obj) {
            return null;
        }
        XStream xStream = BeeXmlFactory.getXStream(obj.getClass(), isNull);
        return xStream.toXML(obj);
    }

    /**
     * 指定 特定类型的别名
     * @param obj
     * @param isNull
     * @param alias
     * @return
     */
    public static String beanToXml(Object obj, boolean isNull,Map<String,Class<?>> alias) {
        if (null == obj) {
            return null;
        }
        XStream xStream = BeeXmlFactory.getXStream(obj.getClass(), isNull,alias);
        return xStream.toXML(obj);
    }

    /**
     * xml 转 bean
     *
     * @param xml   对应的xml格式参数
     * @param clazz xml中对应的属性对应的实体类
     */
    public static <T> T xmlToBean(String xml, Class<T> clazz) {
        if (null == xml) {
            return null;
        }
        XStream xStream = BeeXmlFactory.getXStream(clazz);
        return (T) xStream.fromXML(xml);
    }

    /**
     * xml 转 map工具类 使用了 MapConveter
     *
     * @param xml
     * @return
     */
    public static Map<String, Object> xmlToMap(String xml) {
        XStream xStream = BeeXmlFactory.getXStream(Integer.class);
        xStream.alias("root", Map.class);
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) xStream.fromXML(xml);
        return map;
    }

}
